package com.zmh.controller.wechat;

import java.io.IOException;  
import java.io.PrintWriter;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zmh.common.SignUtil;
import com.zmh.service.wechat.CoreService;

/**
 * Servlet implementation class CoreServlet
 */
@Controller
@RequestMapping("CoreServlet")
public class WeChatController extends HttpServlet {
	private static final long serialVersionUID = 4440739483644821986L;  
//    private static Logger logger = LoggerFactory.getLogger(CoreServlet.class);
	 private final Logger logger = LoggerFactory.getLogger(this.getClass());
	 @Autowired
	 private CoreService coreService;
    /** 
     * 确认请求来自微信服务器 
     */ 
	@ResponseBody
	@RequestMapping(method = { RequestMethod.GET }, produces = "application/json;charset=UTF-8")  
    public void authGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String signature = request.getParameter("signature");  // 微信加密签名
        String timestamp = request.getParameter("timestamp");  // 时间戳  
        String nonce = request.getParameter("nonce");  // 随机数 
        String echostr = request.getParameter("echostr");  // 随机字符串 
        this.logger.info("request: signature:{} timestamp:{} nonce:{} echostr:{}",signature,timestamp,nonce,echostr);
        PrintWriter out = response.getWriter();  
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
        	logger.info("echostr: "+echostr);
        	out.print(echostr);  
        }  
        out.close();  
        out = null;
	}

	/** 
	 * 处理微信服务器发来的消息 
	 */  
    @ResponseBody
    @RequestMapping(method = { RequestMethod.POST }, produces = "application/xml;charset=UTF-8") 
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");  
        // 调用核心业务类接收消息、处理消息  
        String respMessage = coreService.processRequest(request);  
        this.logger.info("返回的消息：{}",respMessage);
        PrintWriter out = response.getWriter();
        out.print(respMessage); 
        out.close();
    } 

}
